<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="首先要区分并发和并行的概念： ​    1.并发强调能够处理多个事务的能力， ​    2.并行是指同时能够处理多个事务。 这里主要讨论高并发下，我们如何利用对程序进行合理的设计，提高系统的并发性。">
<meta property="og:type" content="article">
<meta property="og:title" content="服务器高并发设计模式">
<meta property="og:url" content="http://luqilinok.github.io/2019/07/11/operatorhighconcurrency/index.html">
<meta property="og:site_name" content="Lu QiLin&#39;s Blog">
<meta property="og:description" content="首先要区分并发和并行的概念： ​    1.并发强调能够处理多个事务的能力， ​    2.并行是指同时能够处理多个事务。 这里主要讨论高并发下，我们如何利用对程序进行合理的设计，提高系统的并发性。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://luqilinok.github.io/2019/07/11/operatorhighconcurrency/tongbu.png">
<meta property="og:image" content="http://luqilinok.github.io/2019/07/11/operatorhighconcurrency/courrency_banfanyin.png">
<meta property="og:image" content="http://luqilinok.github.io/2019/07/11/operatorhighconcurrency/courrency_banfanyin_pro.png">
<meta property="og:updated_time" content="2019-07-11T06:00:21.771Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="服务器高并发设计模式">
<meta name="twitter:description" content="首先要区分并发和并行的概念： ​    1.并发强调能够处理多个事务的能力， ​    2.并行是指同时能够处理多个事务。 这里主要讨论高并发下，我们如何利用对程序进行合理的设计，提高系统的并发性。">
<meta name="twitter:image" content="http://luqilinok.github.io/2019/07/11/operatorhighconcurrency/tongbu.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://luqilinok.github.io/2019/07/11/operatorhighconcurrency/">





  <title>服务器高并发设计模式 | Lu QiLin's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Lu QiLin's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-technology">
          <a href="/categories/Technology/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Technology
          </a>
        </li>
      
        
        <li class="menu-item menu-item-notes">
          <a href="/categories/Notes/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            Notes
          </a>
        </li>
      
        
        <li class="menu-item menu-item-personal">
          <a href="/categories/Personal/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Personal
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            About
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://luqilinok.github.io/2019/07/11/operatorhighconcurrency/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="LuQiLin">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Lu QiLin's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">服务器高并发设计模式</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-07-11T13:44:25+08:00">
                2019-07-11
              </time>
            

            

            
          </span>
          
  <span class="post-updated">
    &nbsp; | &nbsp; 更新于
    <time itemprop="dateUpdated" datetime="2019-07-11T14:00:21+08:00" content="2019-07-11">
      2019-07-11
    </time>
  </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Notes/" itemprop="url" rel="index">
                    <span itemprop="name">Notes</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>首先要区分并发和并行的概念：</p>
<p>​    1.并发强调能够处理多个事务的能力，</p>
<p>​    2.并行是指同时能够处理多个事务。</p>
<p>这里主要讨论高并发下，我们如何利用对程序进行合理的设计，提高系统的并发性。</p>
<a id="more"></a>
<hr>
<h1 id="半同步-半异步模式"><a href="#半同步-半异步模式" class="headerlink" title="半同步/半异步模式"></a>半同步/半异步模式</h1><p>在并发模式下，同步和异步的概念与I/O同步异步的概念有所不同，这里的同步是指程序按照代码顺序执行，而异步指的是程序的执行需要系统事件来驱动，比如信号、中断等。</p>
<p><img src="/2019/07/11/operatorhighconcurrency/tongbu.png" alt></p>
<p>异步线程效率高，但编写相对较复杂，难于调试，而同步线程更好相反–逻辑简单，但效率较差。</p>
<p>半同步/半异步模式结合了同步线程和异步线程的优点，它在处理I/O事件时使用异步线程，处理客户逻辑则使用同步线程。这样既满足了客户连接的实时性，同时又能处理多个连接。</p>
<p>实现半同步/半异步需要三个模块：<strong>异步处理模块、同步处理模块和队列模块</strong></p>
<p>在实际的应用中，一般使用<strong>I/O复用epoll</strong>在主线程监听客户端的连接，一旦监听到新的客户请求后，将其封装成请求对象，插入到队列中，同时，很多工作线程可以用来读取并处理该对象的请求。</p>
<p>在这个模式中，最可能阻塞的操作放在同步模块中，这样不会影响到异步模块的处理，不同模块可以使用不同的同步策略，互不干扰，模块间通信则使用IPC实现，但这样则会造成同步模块和异步模块使用队列模块传送数据的时候，由于数据拷贝和上下文切换导致的性能开销。</p>
<hr>
<h1 id="半同步-半反应堆模式"><a href="#半同步-半反应堆模式" class="headerlink" title="半同步/半反应堆模式"></a>半同步/半反应堆模式</h1><p><img src="/2019/07/11/operatorhighconcurrency/courrency_banfanyin.png" alt></p>
<p>半同步/半反应堆模式是半同步/半异步模式的一个变体，在半同步/半异步模式中，工作线程如何选择队列中的请求，是事先设计好的。而在半同步/半反应堆模式中，工作线程通过竞争（例如申请互斥锁）来获得任务的接管权。</p>
<p>半同步/半反应堆可以采用Reactor模式，也可以采用Proactor模式处理，另外两种I/O模式的区别参考：<a href="(/2019/07/11/operatoros/operatorhighconcurrency/">I/O设计模式</a>)</p>
<p>半同步/半反应堆中，异步线程是主线程，负责监听所有的socket事件，如果监听socket上有可读事件发生，指的是新的连接到来，那么异步线程接受它，插入到请求队列中，空闲工作线程开始竞争任务，之后这个线程管理这个socket的所有I/O任务，直到客户关闭连接，工作线程各自监听管理不同的事件，所以不需要通信，每个线程都是异步模式。</p>
<p>缺点：对此进行队列操作时，都需要加锁解锁，从而消耗CPU事件，另外一个线程同一时间只能处理一个客户请求，如果队列中积累了很多任务，如果增加工作线程，工作线程的切换也会耗费大量CPU时间。</p>
<p>改进：工作线程可以调用epoll_wait，这样一个工作线程也可以处理多个客户请求。</p>
<p><img src="/2019/07/11/operatorhighconcurrency/courrency_banfanyin_pro.png" alt></p>
<hr>
<h1 id="领导者-追随者模式"><a href="#领导者-追随者模式" class="headerlink" title="领导者/追随者模式"></a>领导者/追随者模式</h1><p>领导者/追随者模式是指多个工作线程轮流监听、分发、处理事件的一种模式。在任意事件，程序都仅有一个领导者线程，它负责监听I/O事件。其他线程都是追随者，他们休眠在线程池中等待新的领导者。当领导者检测到I/O事件时，首先从线程池中选出新的领导者线程，然后处理I/O事件。此时，新的领导者等待新的I/O事件，旧的领导者处理I/O事件，实现并发。</p>
<p><strong>领导者/追随者最大的优点在于，它是自己监听I/O事件并处理客户请求</strong>，也就是说从接收到处理都是在同一线程中完成，所以不需要在线程之间传递任何额外的数据，也不用在线程间同步对队列的访问。<strong>但也有一个明显的缺点，就是只支持一种事件源集合，所以导致它不能像其他模式让每个线程独立处理不同的客户请求。</strong></p>
<hr>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/07/11/operatoros/" rel="next" title="操作系统基础知识">
                <i class="fa fa-chevron-left"></i> 操作系统基础知识
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/11/linuxcomputersystem/" rel="prev" title="计算机系统组成">
                计算机系统组成 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">LuQiLin</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">80</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">categories</span>
                
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#半同步-半异步模式"><span class="nav-number">1.</span> <span class="nav-text">半同步/半异步模式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#半同步-半反应堆模式"><span class="nav-number">2.</span> <span class="nav-text">半同步/半反应堆模式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#领导者-追随者模式"><span class="nav-number">3.</span> <span class="nav-text">领导者/追随者模式</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LuQiLin</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
